package com.platform.apex.util;

import java.util.Set;
import java.util.List;
import java.util.Map;
import java.util.HashMap; 
import java.lang.reflect.Constructor;

import com.google.common.reflect.ClassPath;
import com.google.common.reflect.ClassPath.ClassInfo;

public class MetadataStorageTablesConfig {

	private static final Logger log = new Logger(MetadataStorageTablesConfig.class);

	private static Map<String, TableDDL> ALL_TABLE_DDL_MAP = new HashMap<String, TableDDL>();
	
	private static boolean isDdlLoaded = false;
	{
		if (!isDdlLoaded) {
			try {
				ClassLoader ddlClsLoader = TableDDL.class.getClassLoader();
				String ddlPackage = TableDDL.class.getPackage().getName();

				ClassPath clsPath = ClassPath.from(ddlClsLoader);
				Set<ClassInfo> classInfoSet = clsPath.getTopLevelClassesRecursive(ddlPackage);
				for (ClassInfo clsInfo : classInfoSet) {
					Class currCls = clsInfo.load();
					if (!currCls.isInterface()) {
						Constructor constructor = currCls.getConstructor();
						Object clsInst = constructor.newInstance();
						if (clsInst instanceof TableDDL) {
							TableDDL tableDDL = (TableDDL) clsInst;
							log.info("Find declared table ddl {%s}", tableDDL.tableName());
							ALL_TABLE_DDL_MAP.put(tableDDL.tableName(), tableDDL);
						}
					}
				}
				isDdlLoaded = true;
			} catch (Exception ex) {
				ex.printStackTrace();
			}
		}
	}

	private final List<String> usedTableList;

	/**
	 * usedTableList is null, use all table ddl
	 * 
	 * @param usedTableList
	 */
	public MetadataStorageTablesConfig(List<String> usedTableList) {
		this.usedTableList = usedTableList;
	}

	public Map<String, TableDDL> getUsedTableDDL() {
		Map<String, TableDDL> usedTableDDLMap = new HashMap<String, TableDDL>();

		if (usedTableList == null || usedTableList.size() == 0) {
			usedTableDDLMap.putAll(ALL_TABLE_DDL_MAP);
		} else {
			for (String tableName : usedTableList) {
				TableDDL tableDDL = ALL_TABLE_DDL_MAP.get(tableName);
				if (tableDDL != null) {
					usedTableDDLMap.put(tableName, tableDDL);
				}
			}
		}
		return usedTableDDLMap;
	}
}
